"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DeleteEditableAction = void 0;
exports.SaveEditableAction = SaveEditableAction;
exports.default = void 0;
exports.defaultActionRender = defaultActionRender;
exports.editableRowByKey = editableRowByKey;
exports.recordKeyToString = void 0;

var _regeneratorRuntime2 = _interopRequireDefault(require("@babel/runtime/helpers/regeneratorRuntime"));

var _toArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toArray"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _objectSpread3 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _jsxRuntime = require("react/jsx-runtime");

var _icons = require("@ant-design/icons");

var _proProvider = require("@ant-design/pro-provider");

var _antdV = require("antd-v4");

var _useLazyKVMap3 = _interopRequireDefault(require("antd-v4/lib/table/hooks/useLazyKVMap"));

var _useMergedState3 = _interopRequireDefault(require("rc-util/lib/hooks/useMergedState"));

var _get = _interopRequireDefault(require("rc-util/lib/utils/get"));

var _set = _interopRequireDefault(require("rc-util/lib/utils/set"));

var _warning = require("rc-util/lib/warning");

var _react = require("react");

var _ = require("..");

var _ProFormContext = _interopRequireDefault(require("../components/ProFormContext"));

var _useDeepCompareEffect = require("../hooks/useDeepCompareEffect");

var _usePrevious = _interopRequireDefault(require("../hooks/usePrevious"));

var _merge = require("../merge");

var _useMountMergeState5 = _interopRequireDefault(require("../useMountMergeState"));

var _excluded = ["map_row_parentKey", "map_row_key"],
    _excluded2 = ["map_row_key"];

var recordKeyToString = function recordKeyToString(rowKey) {
  if (Array.isArray(rowKey)) return rowKey.join(',');
  return rowKey;
};
/**
 * 使用map 来删除数据，性能一般 但是准确率比较高
 *
 * @param params
 * @param action
 */


exports.recordKeyToString = recordKeyToString;

function editableRowByKey(params, action) {
  var _recordKeyToString;

  var getRowKey = params.getRowKey,
      row = params.row,
      data = params.data,
      childrenColumnName = params.childrenColumnName;
  var key = (_recordKeyToString = recordKeyToString(params.key)) === null || _recordKeyToString === void 0 ? void 0 : _recordKeyToString.toString();
  var kvMap = new Map();
  /**
   * 打平这个数组
   *
   * @param records
   * @param parentKey
   */

  function dig(records, map_row_parentKey, map_row_index) {
    records.forEach(function (record, index) {
      var eachIndex = (map_row_index || 0) * 10 + index;
      var recordKey = getRowKey(record, eachIndex).toString(); // children 取在前面方便拼的时候按照反顺序放回去

      if (record && (0, _typeof2.default)(record) === 'object' && childrenColumnName in record) {
        dig(record[childrenColumnName] || [], recordKey, eachIndex);
      }

      var newRecord = (0, _objectSpread3.default)((0, _objectSpread3.default)({}, record), {}, {
        map_row_key: recordKey,
        children: undefined,
        map_row_parentKey: map_row_parentKey
      });
      delete newRecord.children;

      if (!map_row_parentKey) {
        delete newRecord.map_row_parentKey;
      }

      kvMap.set(recordKey, newRecord);
    });
  }

  if (action === 'top') {
    kvMap.set(key, (0, _objectSpread3.default)((0, _objectSpread3.default)({}, kvMap.get(key)), row));
  }

  dig(data);

  if (action === 'update') {
    kvMap.set(key, (0, _objectSpread3.default)((0, _objectSpread3.default)({}, kvMap.get(key)), row));
  }

  if (action === 'delete') {
    kvMap.delete(key);
  }

  var fill = function fill(map) {
    var kvArrayMap = new Map();
    var kvSource = [];
    map.forEach(function (value) {
      if (value.map_row_parentKey) {
        // @ts-ignore
        var map_row_parentKey = value.map_row_parentKey,
            map_row_key = value.map_row_key,
            reset = (0, _objectWithoutProperties2.default)(value, _excluded);

        if (kvArrayMap.has(map_row_key)) {
          reset[childrenColumnName] = kvArrayMap.get(map_row_key);
        }

        kvArrayMap.set(map_row_parentKey, [].concat((0, _toConsumableArray2.default)(kvArrayMap.get(map_row_parentKey) || []), [reset]));
      }
    });
    map.forEach(function (value) {
      if (!value.map_row_parentKey) {
        // @ts-ignore
        var map_row_key = value.map_row_key,
            rest = (0, _objectWithoutProperties2.default)(value, _excluded2);

        if (kvArrayMap.has(map_row_key)) {
          var item = (0, _objectSpread3.default)((0, _objectSpread3.default)({}, rest), {}, (0, _defineProperty2.default)({}, childrenColumnName, kvArrayMap.get(map_row_key)));
          kvSource.push(item);
          return;
        }

        kvSource.push(rest);
      }
    });
    return kvSource;
  };

  var source = fill(kvMap);
  return source;
}
/**
 * 保存按钮的dom
 *
 * @param ActionRenderConfig
 */


function SaveEditableAction(_ref) {
  var recordKey = _ref.recordKey,
      onSave = _ref.onSave,
      form = _ref.form,
      row = _ref.row,
      children = _ref.children,
      newLineConfig = _ref.newLineConfig,
      editorType = _ref.editorType,
      tableName = _ref.tableName;
  var context = (0, _react.useContext)(_ProFormContext.default);

  var _useMountMergeState = (0, _useMountMergeState5.default)(false),
      _useMountMergeState2 = (0, _slicedToArray2.default)(_useMountMergeState, 2),
      loading = _useMountMergeState2[0],
      setLoading = _useMountMergeState2[1];

  return (0, _jsxRuntime.jsxs)("a", {
    onClick: function () {
      var _onClick = (0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee(e) {
        var _context$getFieldForm, isMapEditor, namePath, fields, _recordKey, recordKeyPath, curValue, data, res;

        return (0, _regeneratorRuntime2.default)().wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                e.stopPropagation();
                e.preventDefault();
                _context.prev = 2;
                isMapEditor = editorType === 'Map'; // 为了兼容类型为 array 的 dataIndex,当 recordKey 是一个数组时，用于获取表单值的 key 只取第一项，
                // 从表单中获取回来之后，再根据 namepath 获取具体的某个字段并设置

                namePath = [tableName, Array.isArray(recordKey) ? recordKey[0] : recordKey].map(function (key) {
                  return key === null || key === void 0 ? void 0 : key.toString();
                }).flat(1).filter(Boolean);
                setLoading(true); // @ts-expect-error

                _context.next = 8;
                return form.validateFields(namePath, {
                  recursive: true
                });

              case 8:
                fields = ((_context$getFieldForm = context.getFieldFormatValue) === null || _context$getFieldForm === void 0 ? void 0 : _context$getFieldForm.call(context, namePath)) || form.getFieldValue(namePath); // 处理 dataIndex 为数组的情况

                if (Array.isArray(recordKey) && recordKey.length > 1) {
                  // 获取 namepath
                  _recordKey = (0, _toArray2.default)(recordKey), recordKeyPath = _recordKey.slice(1); // 将目标值获取出来并设置到 fields 当中

                  curValue = (0, _get.default)(fields, recordKeyPath);
                  (0, _set.default)(fields, recordKeyPath, curValue);
                }

                data = isMapEditor ? (0, _set.default)({}, namePath, fields, true) : fields; // 获取数据并保存

                _context.next = 13;
                return onSave === null || onSave === void 0 ? void 0 : onSave(recordKey, // 如果是 map 模式，fields 就是一个值，所以需要set 到对象中
                // 数据模式 fields 是一个对象，所以不需要
                (0, _merge.merge)({}, row, data), row, newLineConfig);

              case 13:
                res = _context.sent;
                setLoading(false);
                return _context.abrupt("return", res);

              case 18:
                _context.prev = 18;
                _context.t0 = _context["catch"](2);
                // eslint-disable-next-line no-console
                console.log(_context.t0);
                setLoading(false);
                return _context.abrupt("return", null);

              case 23:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, null, [[2, 18]]);
      }));

      function onClick(_x) {
        return _onClick.apply(this, arguments);
      }

      return onClick;
    }(),
    children: [loading ? (0, _jsxRuntime.jsx)(_icons.LoadingOutlined, {
      style: {
        marginRight: 8
      }
    }) : null, children || '保存']
  }, "save");
}
/**
 * 删除按钮 dom
 *
 * @param ActionRenderConfig
 */


var DeleteEditableAction = function DeleteEditableAction(_ref2) {
  var recordKey = _ref2.recordKey,
      onDelete = _ref2.onDelete,
      row = _ref2.row,
      children = _ref2.children,
      deletePopconfirmMessage = _ref2.deletePopconfirmMessage,
      cancelEditable = _ref2.cancelEditable;

  var _useMountMergeState3 = (0, _useMountMergeState5.default)(function () {
    return false;
  }),
      _useMountMergeState4 = (0, _slicedToArray2.default)(_useMountMergeState3, 2),
      loading = _useMountMergeState4[0],
      setLoading = _useMountMergeState4[1];

  var onConfirm = /*#__PURE__*/function () {
    var _ref3 = (0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee2() {
      var res;
      return (0, _regeneratorRuntime2.default)().wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.prev = 0;
              setLoading(true);
              _context2.next = 4;
              return onDelete === null || onDelete === void 0 ? void 0 : onDelete(recordKey, row);

            case 4:
              res = _context2.sent;
              setLoading(false);
              setTimeout(function () {
                // 删除之后解除编辑状态，防止新建一行失效
                cancelEditable(recordKey);
              }, 0);
              return _context2.abrupt("return", res);

            case 10:
              _context2.prev = 10;
              _context2.t0 = _context2["catch"](0);
              // eslint-disable-next-line no-console
              console.log(_context2.t0);
              setLoading(false);
              return _context2.abrupt("return", null);

            case 15:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[0, 10]]);
    }));

    return function onConfirm() {
      return _ref3.apply(this, arguments);
    };
  }();

  return children !== false ? (0, _jsxRuntime.jsx)(_antdV.Popconfirm, {
    title: deletePopconfirmMessage,
    onConfirm: onConfirm,
    children: (0, _jsxRuntime.jsxs)("a", {
      children: [loading ? (0, _jsxRuntime.jsx)(_icons.LoadingOutlined, {
        style: {
          marginRight: 8
        }
      }) : null, children || '删除']
    })
  }, "delete") : null;
};

exports.DeleteEditableAction = DeleteEditableAction;

var CancelEditableAction = function CancelEditableAction(props) {
  var recordKey = props.recordKey,
      tableName = props.tableName,
      newLineConfig = props.newLineConfig,
      form = props.form,
      editorType = props.editorType,
      onCancel = props.onCancel,
      cancelEditable = props.cancelEditable,
      row = props.row,
      cancelText = props.cancelText;
  var context = (0, _react.useContext)(_ProFormContext.default);
  return (0, _jsxRuntime.jsx)("a", {
    onClick: function () {
      var _onClick2 = (0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee3(e) {
        var _context$getFieldForm2;

        var isMapEditor, namePath, fields, record, res;
        return (0, _regeneratorRuntime2.default)().wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                e.stopPropagation();
                e.preventDefault();
                isMapEditor = editorType === 'Map';
                namePath = [tableName, recordKey].flat(1).filter(Boolean);
                fields = ((_context$getFieldForm2 = context.getFieldFormatValue) === null || _context$getFieldForm2 === void 0 ? void 0 : _context$getFieldForm2.call(context, namePath)) || form.getFieldValue(namePath);
                record = isMapEditor ? (0, _set.default)({}, namePath, fields) : fields;
                _context3.next = 8;
                return onCancel === null || onCancel === void 0 ? void 0 : onCancel(recordKey, record, row, newLineConfig);

              case 8:
                res = _context3.sent;
                cancelEditable(recordKey);
                /** 充值为默认值，不然编辑的行会丢掉 */

                form.setFieldsValue((0, _defineProperty2.default)({}, recordKey, isMapEditor ? (0, _get.default)(row, namePath) : row));
                return _context3.abrupt("return", res);

              case 12:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3);
      }));

      function onClick(_x2) {
        return _onClick2.apply(this, arguments);
      }

      return onClick;
    }(),
    children: cancelText || '取消'
  }, "cancel");
};

function defaultActionRender(row, config) {
  var recordKey = config.recordKey,
      newLineConfig = config.newLineConfig,
      saveText = config.saveText,
      deleteText = config.deleteText;
  return [(0, _jsxRuntime.jsx)(SaveEditableAction, (0, _objectSpread3.default)((0, _objectSpread3.default)({}, config), {}, {
    row: row,
    children: saveText
  }), "save"), (newLineConfig === null || newLineConfig === void 0 ? void 0 : newLineConfig.options.recordKey) !== recordKey ? (0, _jsxRuntime.jsx)(DeleteEditableAction, (0, _objectSpread3.default)((0, _objectSpread3.default)({}, config), {}, {
    row: row,
    children: deleteText
  }), "delete") : null, (0, _jsxRuntime.jsx)(CancelEditableAction, (0, _objectSpread3.default)((0, _objectSpread3.default)({}, config), {}, {
    row: row
  }), "cancel")];
}
/**
 * 一个方便的hooks 用于维护编辑的状态
 *
 * @param props
 */


function useEditableArray(props) {
  var _useState = (0, _react.useState)(undefined),
      _useState2 = (0, _slicedToArray2.default)(_useState, 2),
      newLineRecordCache = _useState2[0],
      setNewLineRecordCache = _useState2[1];

  var dataSourceKeyIndexMapRef = (0, _react.useRef)(new Map());
  var newLineRecordRef = (0, _react.useRef)(undefined);
  (0, _useDeepCompareEffect.useDeepCompareEffectDebounce)(function () {
    var map = new Map();

    var loopGetKey = function loopGetKey(dataSource) {
      dataSource === null || dataSource === void 0 ? void 0 : dataSource.forEach(function (record, index) {
        var _recordKeyToString2;

        map.set(index.toString(), recordKeyToString(props.getRowKey(record, -1)));
        map.set((_recordKeyToString2 = recordKeyToString(props.getRowKey(record, -1))) === null || _recordKeyToString2 === void 0 ? void 0 : _recordKeyToString2.toString(), index.toString());

        if (props.childrenColumnName && record[props.childrenColumnName]) {
          loopGetKey(record[props.childrenColumnName]);
        }
      });
    };

    loopGetKey(props.dataSource);
    dataSourceKeyIndexMapRef.current = map;
  }, [props.dataSource]); // 这里这么做是为了存上次的状态，不然每次存一下再拿

  newLineRecordRef.current = newLineRecordCache;
  var editableType = props.type || 'single';

  var _useLazyKVMap = (0, _useLazyKVMap3.default)(props.dataSource, 'children', props.getRowKey),
      _useLazyKVMap2 = (0, _slicedToArray2.default)(_useLazyKVMap, 1),
      getRecordByKey = _useLazyKVMap2[0];

  var _useMergedState = (0, _useMergedState3.default)([], {
    value: props.editableKeys,
    onChange: props.onChange ? function (keys) {
      var _props$onChange;

      props === null || props === void 0 ? void 0 : (_props$onChange = props.onChange) === null || _props$onChange === void 0 ? void 0 : _props$onChange.call(props, // 计算编辑的key
      keys.filter(function (key) {
        return key !== undefined;
      }), // 计算编辑的行
      keys.map(function (key) {
        return getRecordByKey(key);
      }).filter(function (key) {
        return key !== undefined;
      }));
    } : undefined
  }),
      _useMergedState2 = (0, _slicedToArray2.default)(_useMergedState, 2),
      editableKeys = _useMergedState2[0],
      setEditableRowKeys = _useMergedState2[1];
  /** 一个用来标志的set 提供了方便的 api 来去重什么的 */


  var editableKeysSet = (0, _react.useMemo)(function () {
    var keys = editableType === 'single' ? editableKeys === null || editableKeys === void 0 ? void 0 : editableKeys.slice(0, 1) : editableKeys;
    return new Set(keys);
  }, [(editableKeys || []).join(','), editableType]);
  var editableKeysRef = (0, _usePrevious.default)(editableKeys);
  /** 这行是不是编辑状态 */

  var isEditable = (0, _.useRefFunction)(function (row) {
    var _props$getRowKey, _props$getRowKey$toSt, _props$getRowKey2, _props$getRowKey2$toS;

    // 为了兼容一下name 模式的 indexKey，所以需要判断两次，一次是index，一次是没有 index 的
    var recordKeyOrIndex = (_props$getRowKey = props.getRowKey(row, row.index)) === null || _props$getRowKey === void 0 ? void 0 : (_props$getRowKey$toSt = _props$getRowKey.toString) === null || _props$getRowKey$toSt === void 0 ? void 0 : _props$getRowKey$toSt.call(_props$getRowKey); // 这里是不设置 index 的地方

    var recordKey = (_props$getRowKey2 = props.getRowKey(row, -1)) === null || _props$getRowKey2 === void 0 ? void 0 : (_props$getRowKey2$toS = _props$getRowKey2.toString) === null || _props$getRowKey2$toS === void 0 ? void 0 : _props$getRowKey2$toS.call(_props$getRowKey2); // 都转化为了字符串，不然 number 和 string

    var stringEditableKeys = editableKeys.map(function (key) {
      return key === null || key === void 0 ? void 0 : key.toString();
    });
    var stringEditableKeysRef = (editableKeysRef === null || editableKeysRef === void 0 ? void 0 : editableKeysRef.map(function (key) {
      return key === null || key === void 0 ? void 0 : key.toString();
    })) || [];
    var preIsEditable = props.tableName && !!(stringEditableKeysRef === null || stringEditableKeysRef === void 0 ? void 0 : stringEditableKeysRef.includes(recordKey)) || !!(stringEditableKeysRef === null || stringEditableKeysRef === void 0 ? void 0 : stringEditableKeysRef.includes(recordKeyOrIndex));
    return {
      recordKey: recordKey,
      isEditable: props.tableName && (stringEditableKeys === null || stringEditableKeys === void 0 ? void 0 : stringEditableKeys.includes(recordKey)) || (stringEditableKeys === null || stringEditableKeys === void 0 ? void 0 : stringEditableKeys.includes(recordKeyOrIndex)),
      preIsEditable: preIsEditable
    };
  });
  /**
   * 进入编辑状态
   *
   * @param recordKey
   */

  var startEditable = (0, _.useRefFunction)(function (recordKey) {
    // 如果是单行的话，不允许多行编辑
    if (editableKeysSet.size > 0 && editableType === 'single' && props.onlyOneLineEditorAlertMessage !== false) {
      _antdV.message.warn(props.onlyOneLineEditorAlertMessage || '只能同时编辑一行');

      return false;
    }

    editableKeysSet.add(recordKey);
    setEditableRowKeys(Array.from(editableKeysSet));
    return true;
  });
  /**
   * 退出编辑状态
   *
   * @param recordKey
   */

  var cancelEditable = (0, _.useRefFunction)(function (recordKey, needReTry) {
    var relayKey = recordKeyToString(recordKey).toString();
    var key = dataSourceKeyIndexMapRef.current.get(relayKey);
    /** 如果没找到key，转化一下再去找 */

    if (!editableKeysSet.has(relayKey) && key && (needReTry !== null && needReTry !== void 0 ? needReTry : true) && props.tableName) {
      cancelEditable(key, false);
      return;
    }
    /** 如果这个是 new Line 直接删除 */


    if (newLineRecordCache && newLineRecordCache.options.recordKey === recordKey) {
      setNewLineRecordCache(undefined);
    }

    editableKeysSet.delete(relayKey);
    editableKeysSet.delete(recordKeyToString(recordKey));
    setEditableRowKeys(Array.from(editableKeysSet));
    return true;
  });
  var propsOnValuesChange = (0, _.useDebounceFn)( /*#__PURE__*/(0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee4() {
    var _props$onValuesChange;

    var _len,
        rest,
        _key,
        _args4 = arguments;

    return (0, _regeneratorRuntime2.default)().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            for (_len = _args4.length, rest = new Array(_len), _key = 0; _key < _len; _key++) {
              rest[_key] = _args4[_key];
            }

            //@ts-ignore
            (_props$onValuesChange = props.onValuesChange) === null || _props$onValuesChange === void 0 ? void 0 : _props$onValuesChange.call.apply(_props$onValuesChange, [props].concat(rest));

          case 2:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4);
  })), 64);
  var onValuesChange = (0, _.useRefFunction)(function (value, values) {
    var _Object$keys$pop;

    if (!props.onValuesChange) {
      return;
    }

    var dataSource = props.dataSource; // 这里是把正在编辑中的所有表单数据都修改掉
    // 不然会用 props 里面的 dataSource，数据只有正在编辑中的
    // Object.keys(get(values, [props.tableName || ''].flat(1)) || values).forEach((recordKey) => {

    editableKeys.forEach(function (eachRecordKey) {
      if ((newLineRecordCache === null || newLineRecordCache === void 0 ? void 0 : newLineRecordCache.options.recordKey) === eachRecordKey) return;
      var recordKey = eachRecordKey.toString(); // 如果数据在这个 form 中没有展示，也不显示

      var editRow = (0, _get.default)(values, [props.tableName || '', recordKey].flat(1).filter(function (key) {
        return key || key === 0;
      }));
      if (!editRow) return;
      dataSource = editableRowByKey({
        data: dataSource,
        getRowKey: props.getRowKey,
        row: editRow,
        key: recordKey,
        childrenColumnName: props.childrenColumnName || 'children'
      }, 'update');
    });
    var relayValue = props.tableName ? (0, _get.default)(value, [props.tableName || ''].flat(1)) : value;
    var recordKey = (_Object$keys$pop = Object.keys(relayValue || {}).pop()) === null || _Object$keys$pop === void 0 ? void 0 : _Object$keys$pop.toString(); //从form 和 cache 中取得数据

    var newLineRecordData = (0, _objectSpread3.default)((0, _objectSpread3.default)({}, newLineRecordCache === null || newLineRecordCache === void 0 ? void 0 : newLineRecordCache.defaultValue), (0, _get.default)(values, [props.tableName || '', recordKey.toString()].flat(1).filter(function (key) {
      return key || key === 0;
    })));
    /** 如果已经在 dataSource 中存在了，直接 find */

    var editRow = dataSourceKeyIndexMapRef.current.has(recordKeyToString(recordKey)) ? dataSource.find(function (item, index) {
      var _props$getRowKey3;

      var key = (_props$getRowKey3 = props.getRowKey(item, index)) === null || _props$getRowKey3 === void 0 ? void 0 : _props$getRowKey3.toString();
      return key === recordKey;
    }) : newLineRecordData;
    propsOnValuesChange.run(editRow || newLineRecordData, dataSource);
  });
  /**
   * 同时只能支持一行,取消之后数据消息，不会触发 dataSource
   *
   * @param row
   * @param options
   * @name 增加新的行
   */

  var addEditRecord = (0, _.useRefFunction)(function (row, options) {
    if ((options === null || options === void 0 ? void 0 : options.parentKey) && !dataSourceKeyIndexMapRef.current.has(recordKeyToString(options === null || options === void 0 ? void 0 : options.parentKey).toString())) {
      console.warn("can't find record by key", options === null || options === void 0 ? void 0 : options.parentKey);
      return false;
    } // 暂时不支持多行新增


    if (newLineRecordRef.current && props.onlyAddOneLineAlertMessage !== false) {
      _antdV.message.warn(props.onlyAddOneLineAlertMessage || '只能新增一行');

      return false;
    } // 如果是单行的话，不允许多行编辑


    if (editableKeysSet.size > 0 && editableType === 'single' && props.onlyOneLineEditorAlertMessage !== false) {
      _antdV.message.warn(props.onlyOneLineEditorAlertMessage || '只能同时编辑一行');

      return false;
    } // 防止多次渲染


    var recordKey = props.getRowKey(row, -1);

    if (!recordKey) {
      (0, _warning.noteOnce)(!!recordKey, '请设置 recordCreatorProps.record 并返回一个唯一的key  \n  https://procomponents.ant.design/components/editable-table#editable-%E6%96%B0%E5%BB%BA%E8%A1%8C');
      throw new Error('请设置 recordCreatorProps.record 并返回一个唯一的key');
    }

    editableKeysSet.add(recordKey);
    setEditableRowKeys(Array.from(editableKeysSet)); // 如果是dataSource 新增模式的话，取消再开始编辑，
    // 这样就可以把新增到 dataSource的数据进入编辑模式了
    // [a,b,cache] => [a,b,c]

    if ((options === null || options === void 0 ? void 0 : options.newRecordType) === 'dataSource' || props.tableName) {
      var _recordKeyToString3;

      var actionProps = {
        data: props.dataSource,
        getRowKey: props.getRowKey,
        row: (0, _objectSpread3.default)((0, _objectSpread3.default)({}, row), {}, {
          map_row_parentKey: (options === null || options === void 0 ? void 0 : options.parentKey) ? (_recordKeyToString3 = recordKeyToString(options === null || options === void 0 ? void 0 : options.parentKey)) === null || _recordKeyToString3 === void 0 ? void 0 : _recordKeyToString3.toString() : undefined
        }),
        key: recordKey,
        childrenColumnName: props.childrenColumnName || 'children'
      };
      props.setDataSource(editableRowByKey(actionProps, (options === null || options === void 0 ? void 0 : options.position) === 'top' ? 'top' : 'update'));
    } else {
      setNewLineRecordCache({
        defaultValue: row,
        options: (0, _objectSpread3.default)((0, _objectSpread3.default)({}, options), {}, {
          recordKey: recordKey
        })
      });
    }

    return true;
  }); // Internationalization

  var intl = (0, _proProvider.useIntl)();
  var saveText = (props === null || props === void 0 ? void 0 : props.saveText) || intl.getMessage('editableTable.action.save', '保存');
  var deleteText = (props === null || props === void 0 ? void 0 : props.deleteText) || intl.getMessage('editableTable.action.delete', '删除');
  var cancelText = (props === null || props === void 0 ? void 0 : props.cancelText) || intl.getMessage('editableTable.action.cancel', '取消');
  var actionSaveRef = (0, _.useRefFunction)( /*#__PURE__*/function () {
    var _ref5 = (0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee5(recordKey, editRow, originRow, newLine) {
      var _props$onSave, _recordKeyToString4, _options$parentKey;

      var _ref6, options, res, actionProps;

      return (0, _regeneratorRuntime2.default)().wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              _ref6 = newLine || newLineRecordRef.current || {}, options = _ref6.options;
              _context5.next = 3;
              return props === null || props === void 0 ? void 0 : (_props$onSave = props.onSave) === null || _props$onSave === void 0 ? void 0 : _props$onSave.call(props, recordKey, editRow, originRow, newLine);

            case 3:
              res = _context5.sent;
              // 保存时解除编辑模式
              cancelEditable(recordKey);

              if (!(!(options === null || options === void 0 ? void 0 : options.parentKey) && (options === null || options === void 0 ? void 0 : options.recordKey) === recordKey)) {
                _context5.next = 8;
                break;
              }

              if ((options === null || options === void 0 ? void 0 : options.position) === 'top') {
                props.setDataSource([editRow].concat((0, _toConsumableArray2.default)(props.dataSource)));
              } else {
                props.setDataSource([].concat((0, _toConsumableArray2.default)(props.dataSource), [editRow]));
              }

              return _context5.abrupt("return", res);

            case 8:
              actionProps = {
                data: props.dataSource,
                getRowKey: props.getRowKey,
                row: options ? (0, _objectSpread3.default)((0, _objectSpread3.default)({}, editRow), {}, {
                  map_row_parentKey: (_recordKeyToString4 = recordKeyToString((_options$parentKey = options === null || options === void 0 ? void 0 : options.parentKey) !== null && _options$parentKey !== void 0 ? _options$parentKey : '')) === null || _recordKeyToString4 === void 0 ? void 0 : _recordKeyToString4.toString()
                }) : editRow,
                key: recordKey,
                childrenColumnName: props.childrenColumnName || 'children'
              };
              props.setDataSource(editableRowByKey(actionProps, (options === null || options === void 0 ? void 0 : options.position) === 'top' ? 'top' : 'update'));
              return _context5.abrupt("return", res);

            case 11:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5);
    }));

    return function (_x3, _x4, _x5, _x6) {
      return _ref5.apply(this, arguments);
    };
  }());
  var actionDeleteRef = (0, _.useRefFunction)( /*#__PURE__*/function () {
    var _ref7 = (0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee6(recordKey, editRow) {
      var _props$onDelete;

      var actionProps, res;
      return (0, _regeneratorRuntime2.default)().wrap(function _callee6$(_context6) {
        while (1) {
          switch (_context6.prev = _context6.next) {
            case 0:
              actionProps = {
                data: props.dataSource,
                getRowKey: props.getRowKey,
                row: editRow,
                key: recordKey,
                childrenColumnName: props.childrenColumnName || 'children'
              };
              _context6.next = 3;
              return props === null || props === void 0 ? void 0 : (_props$onDelete = props.onDelete) === null || _props$onDelete === void 0 ? void 0 : _props$onDelete.call(props, recordKey, editRow);

            case 3:
              res = _context6.sent;
              props.setDataSource(editableRowByKey(actionProps, 'delete'));
              return _context6.abrupt("return", res);

            case 6:
            case "end":
              return _context6.stop();
          }
        }
      }, _callee6);
    }));

    return function (_x7, _x8) {
      return _ref7.apply(this, arguments);
    };
  }());
  var actionCancelRef = (0, _.useRefFunction)( /*#__PURE__*/function () {
    var _ref8 = (0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee7(recordKey, editRow, originRow, newLine) {
      var _props$onCancel;

      var res;
      return (0, _regeneratorRuntime2.default)().wrap(function _callee7$(_context7) {
        while (1) {
          switch (_context7.prev = _context7.next) {
            case 0:
              _context7.next = 2;
              return props === null || props === void 0 ? void 0 : (_props$onCancel = props.onCancel) === null || _props$onCancel === void 0 ? void 0 : _props$onCancel.call(props, recordKey, editRow, originRow, newLine);

            case 2:
              res = _context7.sent;
              return _context7.abrupt("return", res);

            case 4:
            case "end":
              return _context7.stop();
          }
        }
      }, _callee7);
    }));

    return function (_x9, _x10, _x11, _x12) {
      return _ref8.apply(this, arguments);
    };
  }());

  var actionRender = function actionRender(row, form) {
    var key = props.getRowKey(row, row.index);
    var config = {
      saveText: saveText,
      cancelText: cancelText,
      deleteText: deleteText,
      addEditRecord: addEditRecord,
      recordKey: key,
      cancelEditable: cancelEditable,
      index: row.index,
      tableName: props.tableName,
      newLineConfig: newLineRecordCache,
      onCancel: actionCancelRef,
      onDelete: actionDeleteRef,
      onSave: actionSaveRef,
      form: form,
      editableKeys: editableKeys,
      setEditableRowKeys: setEditableRowKeys,
      deletePopconfirmMessage: props.deletePopconfirmMessage || '删除此行？'
    };
    var defaultDoms = defaultActionRender(row, config);
    if (props.actionRender) return props.actionRender(row, config, {
      save: defaultDoms[0],
      delete: defaultDoms[1],
      cancel: defaultDoms[2]
    });
    return defaultDoms;
  };

  return {
    editableKeys: editableKeys,
    setEditableRowKeys: setEditableRowKeys,
    isEditable: isEditable,
    actionRender: actionRender,
    startEditable: startEditable,
    cancelEditable: cancelEditable,
    addEditRecord: addEditRecord,
    newLineRecord: newLineRecordCache,
    preEditableKeys: editableKeysRef,
    onValuesChange: onValuesChange
  };
}

var _default = useEditableArray;
exports.default = _default;